package com.zjitc.book.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.service.impl.UserServiceImpl;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        if("OPTIONS".equals(request.getMethod())){
//
//        }
        //Authorization-->"Bearer xxxxx"
        String authHeader = request.getHeader("Authorization");

        System.out.println("-------authHeader--------"+authHeader);

        if(StrUtil.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")){
            String token=authHeader.substring(7);
            //解密token
            JWT jwt = JWT.of(token).setKey("123123123123123123".getBytes());
            if(jwt.verify()){
                //如果jwt令牌有效，那么取出放进去的userid，就可以找到该用户的信息
                String username = (String)jwt.getPayload("username");
                Integer userid = Convert.toInt(jwt.getPayload("userid"));

                //效率低
//                MyUserDetails userDetails=(MyUserDetails) userService.loadUserByUsername(username);

                Set<String> auths = stringRedisTemplate.opsForSet().members("user.perms:" + userid);
                List<SimpleGrantedAuthority> authors=new ArrayList<>();
                auths.forEach(auth->authors.add(new SimpleGrantedAuthority(auth)));

                //4. 再让springsecurity接管
                UsernamePasswordAuthenticationToken authenticationToken=
                        new UsernamePasswordAuthenticationToken(username,null,authors);

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        //放行
        filterChain.doFilter(request,response);
    }
}
